package com.cms.action;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import com.action.DefaultAction;
import com.cms.model.AppInfo;
import com.cms.model.AppVersionInfo;
import com.cms.model.Channel;
import com.cms.model.ChannelTerraceInfo;
import com.cms.model.ImportLog;
import com.cms.model.ImportUserChannelData;
import com.cms.model.ImportUserData;
import com.cms.service.AppInfoService;
import com.cms.service.AppInfoServiceImpl;
import com.cms.service.AppVersionInfoServiceImpl;
import com.cms.service.ChannelService;
import com.cms.service.ChannelServiceImpl;
import com.cms.service.ChannelTerraceInfoImpl;
import com.cms.service.ImportLogService;
import com.cms.service.ImportLogServiceImpl;
import com.cms.service.ImportUserDataService;
import com.cms.service.ImportUserDataServiceImpl;
import com.util.Config;
import com.util.ConfigUtil;
import com.util.FileDigest;
import com.util.Util;

public class ImportUserDataAction extends DefaultAction {
private static final long serialVersionUID = 1L;
	
	public ImportUserDataAction()
	{
	}
	private File Filedata;
	private String FiledataFileName;
	private String FiledataContentType;
	private ImportLog logmodel;
	
	List<ImportUserData> datalist = new ArrayList<ImportUserData>();
	AppInfoService appservice = new AppInfoServiceImpl();
	List<AppInfo> applist ;
	List<AppVersionInfo> appversionlist;
	List<Channel> channellist;
	ChannelService channelservice = new ChannelServiceImpl();
	ImportLogService ilservice = new ImportLogServiceImpl();
	ImportUserDataService service = new ImportUserDataServiceImpl();
	public String show()
	{
		return SUCCESS;
	}
	public String view()
	{
		applist = appservice.getAppInfos();
		appversionlist=new AppVersionInfoServiceImpl().getAppVersionInfos();
		channellist = channelservice.getChannels();
		
		List<ChannelTerraceInfo> chterracelist = new ChannelTerraceInfoImpl().getChannelTerraceInfos();
		try{
			POIFSFileSystem fs =new POIFSFileSystem(new FileInputStream(logmodel.getFilesrc()));
	
		    HSSFWorkbook wb = new HSSFWorkbook(fs);
	
		    HSSFSheet sheet = wb.getSheetAt(0);
		    
		    int firstRowNum = sheet.getFirstRowNum();
		    int lastRowNum=sheet.getLastRowNum();
		    if(firstRowNum>=lastRowNum)
		    {
		    	addActionError("数据文件解析错误，请检查重传！");
				return INPUT;
		    }
		    HSSFRow row = null;
		    
		    ImportUserData data = null;
		    for(int i =firstRowNum+1;i<=lastRowNum;i++)
		    {
		    	data = new ImportUserData();
		    	row = sheet.getRow(i);
		    	if(row!=null)
		    	{
		    		HSSFCell cell = row.getCell((short)0);
		    		String day = "";
		    		if(cell!=null)
		    			day = cell.toString().trim();
		    		
		    		cell = row.getCell((short)1);
		    		String appname = "";
		    		if(cell!=null)
		    			appname = cell.toString().trim();
		    		
		    		cell = row.getCell((short)2);
		    		String appversionname = "";
		    		if(cell!=null)
		    			appversionname = cell.toString().trim();
		    		
		    		cell = row.getCell((short)3);
		    		String chid = "";
		    		if(cell!=null)
		    			chid = cell.toString().trim();
		    		
		    		cell = row.getCell((short)4);
		    		String op = "";
		    		if(cell!=null)
		    			op = cell.toString().trim();
		    		
		    		String usersum="0";
		    		cell = row.getCell((short)5);
		    		if(cell!=null && !"".equals(cell.toString().trim()))
		    		{
		    			usersum = cell.toString().trim();
		    			if(usersum.indexOf(".0")>-1)
		    			{
		    				usersum = usersum.replace(".0","");
		    			}
		    		}
		    		String fee="0";
		    		cell = row.getCell((short)6);
		    		if(cell!=null && !"".equals(cell.toString().trim()))
		    		{
		    			fee = cell.toString().trim();
		    			if(fee.indexOf(".0")>-1)
		    			{
		    				fee = fee.replace(".0","");
		    			}
		    		}
		    		
		    		if(!"".equals(day) && !"".equals(usersum))
		    		{
		    			String appnumber = "";
	    				for(int j=0;j<applist.size();j++)
		    			{
		    				if(applist.get(j).getAppname().equals(appname))
		    				{
		    					appnumber = applist.get(j).getAppnumber();
		    					break;
		    				}
		    					
		    			}
	    				if(appnumber==null || appnumber.equals(""))
	    				{
		    				for(int j=0;j<applist.size();j++)
			    			{
			    				if(applist.get(j).getAppname().indexOf(appname)>-1)
			    				{
			    					appnumber = applist.get(j).getAppnumber();
			    					break;
			    				}
			    					
			    			}
	    				}
	    				String appversionnumber="";
	    				if(appversionnumber==null || appversionnumber.equals(""))
	    				{
		    				for(int j=0;j<appversionlist.size();j++)
			    			{
		    					AppVersionInfo av = appversionlist.get(j);
			    				if(av.getAppname().indexOf(appversionname)>-1)
			    				{
			    					appversionnumber = av.getAppversionnumber();
			    					break;
			    				}
			    					
			    			}
	    				}
	    				int d = Integer.parseInt(day.replace("-","").trim());
		    			data.setDay(d);
		    			data.setAppnumber(appnumber);
		    			data.setAppversionnumber(appversionnumber);
		    			int channelid = -1;
		    			for (ChannelTerraceInfo ce : chterracelist) {
							if(ce.getRelevanceid().equals(chid)){
								channelid=ce.getChannelId();
								break;
							}
						}
		    			if(channelid==-1){
		    				throw new Exception("chid未匹配到，请检查！chid:"+chid);
		    			}
		    			data.setChannelid(channelid);
		    			data.setChid(chid);
		    			data.setOperator(op);
		    			data.setSum(Integer.parseInt(usersum.trim()));
		    			data.setFee(Float.parseFloat(fee));
		    			datalist.add(data);
		    		}
		    	}
		    }
	
		}catch(Exception ex)
		{
			addActionError("数据文件解析错误，请检查重传！errmsg:"+ex.getMessage());
			System.out.println("导入数据，不知道哪出问题？"+ex.getMessage());
			return INPUT;
		}
		return SUCCESS;
	}
	public String formatfee(String fee)
	{
		if(fee.endsWith(".0"))
		{
			fee = fee.substring(0,(fee.length()-2));
		}
		return fee;
	}
	int datanumber;
	String msg;
	public String save()
	{
		logmodel.setCreateuser(getAdminLoginName());
		logmodel.setCreatedate(Util.dateToString(new Date()));
		try{
			if(ilservice.insertImportLog(logmodel))
			{
				ImportUserData data;
				for(int i=1;i<=datanumber;i++)
				{
					data = new ImportUserData();
					data.setDatafileid(logmodel.getId());
					int d = Integer.parseInt(getParameter("day"+i));
					data.setDay(d);
					data.setAppnumber(getParameter("appnumber"+i));
					String appversionnumber = getParameter("appversionnumber"+i);
					data.setAppversionnumber(appversionnumber);
					data.setChannelid(Integer.parseInt(getParameter("channelid"+i)));
					String operator = getParameter("operator"+i);
					data.setOperator(operator);
					data.setSum(Integer.parseInt(getParameter("usersum"+i)));
					String chid = getParameter("chid"+i);
					data.setChid(chid);
					data.setFee(Float.parseFloat(getParameter("fee"+i)));
					datalist.add(data);
				}
				if(!service.saveImportUserData(datalist))
				{
					msg = "数据导入：数据导入失败！";
				}
				else{
					msg = "数据导入：数据导入成功！";
					List<ImportUserChannelData> channeldatalist = new ArrayList<ImportUserChannelData>();
					ImportUserChannelData channeldata;
					for(int i =0;i<datalist.size();i++)
					{
						channeldata = new ImportUserChannelData(datalist.get(i));
						channeldatalist.add(channeldata);
					}
					service.saveImportUserChannelData(channeldatalist);
				}
			}else
			{
				msg = "数据导入：数据导入失败！";
			}
		}catch(Exception ex)
		{
			msg = "数据导入：数据导入失败！";
		}
		return SUCCESS;
	}
	public String uploaddatafile()
	{
		if(Filedata!=null)
		{
			String reiconname = FileDigest.getFileMD5(Filedata);
			String filesrc = ConfigUtil.get(Config.SECTIONMANAGE, Config.KEY_IMPORTDATA_SAVE_PATH) + 
			"/"+reiconname;
			saveUploadFile(Filedata,filesrc);
			logmodel = new ImportLog();
			logmodel.setFilename(FiledataFileName);
			logmodel.setRefilename(reiconname);
			logmodel.setFilesrc(filesrc);
		}
		return SUCCESS;
	}
	public File getFiledata() {
		return Filedata;
	}
	public void setFiledata(File filedata) {
		Filedata = filedata;
	}
	public String getFiledataFileName() {
		return FiledataFileName;
	}
	public void setFiledataFileName(String filedataFileName) {
		FiledataFileName = filedataFileName;
	}
	public String getFiledataContentType() {
		return FiledataContentType;
	}
	public void setFiledataContentType(String filedataContentType) {
		FiledataContentType = filedataContentType;
	}
	public ImportLog getLogmodel() {
		return logmodel;
	}
	public void setLogmodel(ImportLog logmodel) {
		this.logmodel = logmodel;
	}
	public List<ImportUserData> getDatalist() {
		return datalist;
	}
	public void setDatalist(List<ImportUserData> datalist) {
		this.datalist = datalist;
	}
	public List<AppInfo> getApplist() {
		return applist;
	}
	public void setApplist(List<AppInfo> applist) {
		this.applist = applist;
	}
	public List<Channel> getChannellist() {
		return channellist;
	}
	public void setChannellist(List<Channel> channellist) {
		this.channellist = channellist;
	}
	public int getDatanumber() {
		return datanumber;
	}
	public void setDatanumber(int datanumber) {
		this.datanumber = datanumber;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public List<AppVersionInfo> getAppversionlist() {
		return appversionlist;
	}
	public void setAppversionlist(List<AppVersionInfo> appversionlist) {
		this.appversionlist = appversionlist;
	}
	
}
